#include "timer.h"
#include "Input.h"

/**
 * @brief 初始化 TIM4，每 1ms 产生一次更新中断
 */
void DIN_Timer_Init(void) {
    TIM_TimeBaseInitTypeDef tim;

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
    TIM_TimeBaseStructInit(&tim);
    tim.TIM_Prescaler   = 72 - 1;
    tim.TIM_Period      = 1000 - 1;   // 1ms
    tim.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM4, &tim);
    TIM_ITConfig(TIM4, TIM_IT_Update, ENABLE);
    TIM_Cmd(TIM4, ENABLE);
    TIM4_NVIC_Config();
}

/**
 * @brief 配置 TIM4 中断优先级
 */
static void TIM4_NVIC_Config(void) {
    NVIC_InitTypeDef nvic;
    nvic.NVIC_IRQChannel                   = TIM4_IRQn;
    nvic.NVIC_IRQChannelPreemptionPriority = 3;
    nvic.NVIC_IRQChannelSubPriority        = 0;
    nvic.NVIC_IRQChannelCmd                = ENABLE;
    NVIC_Init(&nvic);
}

/**
 * @brief TIM4 中断服务程序
 *        清除标志
 */
void TIM4_IRQHandler(void) {
#ifdef OS_TICKS_PER_SEC
    OSIntEnter();
#endif
    if (TIM_GetITStatus(TIM4, TIM_IT_Update) != RESET) {
        TIM_ClearITPendingBit(TIM4, TIM_IT_Update);
        DIN_Proc();
    }
#ifdef OS_TICKS_PER_SEC
    OSIntExit();
#endif
}
